<template>
    <div>
        <head-top></head-top>
        <el-row style="margin-top: 20px;">
  			<el-col :span="12" :offset="4">
		        <el-form :model="formData" :rules="rules" ref="formData" label-width="110px" class="demo-formData">
					<el-form-item label="产品名称" prop="productName">
						<el-input v-model="formData.productName "></el-input>
					</el-form-item>
                    <el-form-item label="产品介绍" prop="productIntroduce">
                    	<el-input v-model="formData.productIntroduce "></el-input>
                    </el-form-item>
                    <el-form-item label="产品库存" prop="productsInventory">
                    	<el-input v-model="formData.productsInventory " type="number"></el-input>
                    </el-form-item>
                    <el-form-item label="产品价格" prop="productPrice">
                    	<el-input v-model="formData.productPrice" type="number"></el-input>
                    </el-form-item>

					<el-form-item label="上传产品封面">
                        <p>{{formData.productImg}}</p>
						<el-upload
						  class="avatar-uploader"
						  :action=posterURI
                          :headers="headers"
						  :show-file-list="false"
						  :on-success="handleShopAvatarScucess"
						  :before-upload="beforeAvatarUpload">
						  <img v-if="formData.productImg" :src="this.$host + formData.productImg" class="avatar">
						  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
						</el-upload>
					</el-form-item>

<!--					<el-form-item label="上传产品轮播图">-->
<!--						<el-upload-->
<!--						  class="avatar-uploader"-->
<!--						  :action="baseUrl + '/v1/addimg/shop'"-->
<!--						  :show-file-list="false"-->
<!--						  :on-success="handleBusinessAvatarScucess"-->
<!--						  :before-upload="beforeAvatarUpload">-->
<!--						  <img v-if="formData.business_license_image" :src="baseImgPath + formData.business_license_image" class="avatar">-->
<!--						  <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--						</el-upload>-->
<!--					</el-form-item>-->
					<el-form-item class="button_submit">
						<el-button type="primary" @click="submitForm('formData')">立即创建</el-button>
					</el-form-item>
				</el-form>
  			</el-col>
  		</el-row>
    </div>
</template>

<script>
    import headTop from '@/components/headTop'
    import {cityGuess, addGood, searchplace, foodCategory} from '@/api/getData'
    import {baseUrl, baseImgPath} from '@/config/env'
    export default {

    	data(){
    		return {
                posterURI:this.$host+"/zk/uploadFileServer/uploadFolder",
    			city: {},
    			formData: {
                    productName:"",
                    createdUser: "",
                    productImg: "",
                    productIntroduce: "",
                    productPrice: "",
                    productsInventory: "",
                    updateUser: ""

                },

                        pickerOptions: {
                          disabledDate(time) {
                            return time.getTime() > Date.now();
                          },
                          shortcuts: [{
                            text: '今天',
                            onClick(picker) {
                              picker.$emit('pick', new Date());
                            }
                          }, {
                            text: '昨天',
                            onClick(picker) {
                              const date = new Date();
                              date.setTime(date.getTime() - 3600 * 1000 * 24);
                              picker.$emit('pick', date);
                            }
                          }, {
                            text: '一周前',
                            onClick(picker) {
                              const date = new Date();
                              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                              picker.$emit('pick', date);
                            }
                          }]
                        },
                        value1: '',
                        value2: '',
		        rules: {
                    productName: [
						{ required: true, message: '请输入产品名字', trigger: 'blur' },
					],
					address: [
						{ required: true, message: '请输入详细地址', trigger: 'blur' }
					],
                    productPrice: [
						{ required: true, message: '请输入产品价格' },
					],
                    productsInventory: [
                        { required: true, message: '请输入库存数量' },
                    ],
				},

			    baseUrl,
			    baseImgPath,
			    categoryOptions: [],
			    selectedCategory: ['快餐便当', '简餐']
    		}
    	},
    	components: {
    		headTop,
    	},
        computed: {
            headers() {
                return {
                    "Authorization": localStorage.getItem('token')
                }
            },
        },
    	mounted(){
    		this.initData();
    	},
    	methods: {
    		async initData(){
    			try{
    				this.city = await cityGuess();
    				const categories = await foodCategory();
    				categories.forEach(item => {
    					if (item.sub_categories.length) {
    						const addnew = {
    							value: item.name,
						        label: item.name,
						        children: []
    						}
    						item.sub_categories.forEach((subitem, index) => {
    							if (index == 0) {
    								return
    							}
    							addnew.children.push({
    								value: subitem.name,
						        	label: subitem.name,
    							})
    						})
    						this.categoryOptions.push(addnew)

    					}
    				})
    			}catch(err){
    				console.log(err);
    			}
    		},
    		async querySearchAsync(queryString, cb) {
    			if (queryString) {
	    			try{
	    				const cityList = await searchplace(this.city.id, queryString);
	    				if (cityList instanceof Array) {
		    				cityList.map(item => {
		    					item.value = item.address;
		    					return item;
		    				})
		    				cb(cityList)
	    				}
	    			}catch(err){
	    				console.log(err)
	    			}
    			}
		    },
		    addressSelect(address){
		    	this.formData.latitude = address.latitude;
		    	this.formData.longitude = address.longitude;
		    	console.log(this.formData.latitude, this.formData.longitude)
		    },
			handleShopAvatarScucess(res, file) {
                    this.formData.productImg = res.data;
                    console.log(res.data)
			},
			handleBusinessAvatarScucess(res, file) {
				if (res.status == 1) {
					this.formData.business_license_image = res.image_path;
				}else{
					this.$message.error('上传图片失败！');
				}
			},
			handleServiceAvatarScucess(res, file) {
				if (res.status == 1) {
					this.formData.catering_service_license_image = res.image_path;
				}else{
					this.$message.error('上传图片失败！');
				}
			},
			beforeAvatarUpload(file) {
				const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isRightType) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isRightType && isLt2M;
			},
			tableRowClassName(row, index) {
		        if (index === 1) {
		        	return 'info-row';
		        } else if (index === 3) {
		        	return 'positive-row';
		        }
		        return '';
		    },

		    handleDelete(index){
		    	this.activities.splice(index, 1)
		    },
		    submitForm(formName) {
				this.$refs[formName].validate(async (valid) => {
					if (valid) {
						try{
							var that = this;
                            this.$axios.post(this.$host2+"/zk/all-products/",that.formData,{
                                headers: {
                                    // 'Content-Type': 'application/x-www-form-urlencoded',
                                    "Authorization": localStorage.getItem('token')

                                }
                            }).then(
                                res=>{
                                    if(res.data.code==200)
                                    {
                                        this.$message({
                                            type: 'success',
                                            message: '添加成功'
                                        });
                                        that.formData = {
                                        productName:"",
                                            createdUser: "",
                                            productImg: "",
                                            productIntroduce: "",
                                            productPrice: "",
                                            productsInventory: "",
                                            updateUser: ""

                                    };
                                        that.$router.push("goodList");
                                    }
                                }
                            ).catch(error=>
                            {
                                console.log(error)
                                this.$message({
                                    type: 'error',
                                    message: error
                                });

                            });

						}catch(err){
							console.log(err)
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: '请检查输入是否正确',
							offset: 100
						});
						return false;
					}
				});
			},
		}
    }
</script>

<style lang="less">
	@import '../style/mixin';
	.button_submit{
		text-align: center;
	}
	.avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
	    border-color: #20a0ff;
	}
	.avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 120px;
	    height: 120px;
	    line-height: 120px;
	    text-align: center;
	}
	.avatar {
	    width: 120px;
	    height: 120px;
	    display: block;
	}
	.el-table .info-row {
	    background: #c9e5f5;
	}

	.el-table .positive-row {
	    background: #e2f0e4;
	}
</style>
